package org.tio.sitexxx.im.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.core.intf.GroupListener;
import org.tio.sitexxx.im.common.Command;
import org.tio.sitexxx.im.common.ImPacket;
import org.tio.sitexxx.im.common.bs.LeaveGroupNtf;
import org.tio.sitexxx.im.common.utils.ImUtils;
import org.tio.sitexxx.im.server.handler.PageOnlineReqHandler;
import org.tio.sitexxx.service.vo.Const;
import org.tio.sitexxx.service.vo.GroupStat;
import org.tio.sitexxx.service.vo.SimpleUser;

/**
 * @author tanyaowu
 * 2016年5月13日 下午10:38:36
 */
public class TioSiteImGroupListener implements GroupListener {
	@SuppressWarnings("unused")
	private static Logger log = LoggerFactory.getLogger(TioSiteImGroupListener.class);

	public static TioSiteImGroupListener me = new TioSiteImGroupListener();

	/**
	 * @param args
	 * @author tanyaowu
	 */
	public static void main(String[] args) {

	}

	/**
	 *
	 * @author tanyaowu
	 */
	protected TioSiteImGroupListener() {
	}

	/**
	 * @param channelContext
	 * @param group
	 * @throws Exception
	 * @author tanyaowu
	 */
	@Override
	public void onAfterBind(ChannelContext channelContext, String group) throws Exception {
	}

	/**
	 * @param channelContext
	 * @param group
	 * @throws Exception
	 * @author tanyaowu
	 */
	@Override
	public void onAfterUnbind(ChannelContext channelContext, String group) throws Exception {
		PageOnlineReqHandler.ME.clearCache(group);//进出群组要清空在线观众列表的数据

		boolean con = !group.startsWith(Const.ImGroupType.PREFIX);

		// 暂时获取在所有页面上的用户
		con = org.tio.sitexxx.service.vo.Const.ImGroupType.ALL_IN_ONE.equals(group);

		if (con) {
			SimpleUser simpleUser = ImUtils.getHandshakeSimpleUser(channelContext);
			LeaveGroupNtf leaveGroupNtf = new LeaveGroupNtf(group, simpleUser);

			GroupStat groupStat = Ims.createGroupStat(group);

			// 暂时获取在所有页面上的用户
			groupStat = Ims.createGroupStat(org.tio.sitexxx.service.vo.Const.ImGroupType.ALL_IN_ONE);
			leaveGroupNtf.setG(org.tio.sitexxx.service.vo.Const.ImGroupType.ALL_IN_ONE);

			leaveGroupNtf.setOnline(groupStat.getOnline());
			ImPacket imPacket = new ImPacket(Command.LEAVE_GROUP_NTY, leaveGroupNtf);

			Ims.sendToGroup(group, imPacket);
		}
	}

}
